package com.hrt.web.member.controller;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.hrt.bean.HRTMember;
import com.hrt.util.GetAgeUtil;
import com.hrt.util.MD5Tool;
import com.hrt.util.RamUtil;
import com.hrt.util.ReadFromFile;
import com.hrt.util.WebParams;
import com.hrt.web.member.service.HRTMemberService;

@Controller
@RequestMapping("HRTWEB")
public class HRTMemberControllor {

	@Autowired
	private HRTMemberService hrtMemberService;

	/**
	 * @param member
	 * @param request
	 * @return 会员注册
	 */
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public ModelAndView UserRegister(
			@ModelAttribute("userInfo") HRTMember member,
			HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();
		System.out.println("register");
		String email = member.getMail();
		String pwd = member.getPassword();
		String phone = member.getMobile();
		String borth = request.getParameter("myborth");
		String mbrName = member.getMbrName();
		String sex = request.getParameter("sex");
		Date registTime = new Date();

		// 根据生日计算年龄
		int age = GetAgeUtil.getAge(borth, GetAgeUtil.getStringDate());

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try {
			date = sdf.parse(borth);
		} catch (ParseException e1) {
			e1.printStackTrace();
		}
		String checkNum = request.getParameter("hrtMemberCheckout");
		HttpSession session = request.getSession();
		String randCheckCode = (String) session.getAttribute("randCheckCode");

		boolean checkNumB = randCheckCode.equalsIgnoreCase(checkNum);
		boolean usernameB = hrtMemberService.findMember(email);
		/*
		 * if(new Boolean(checkNumB)==null) {
		 * 
		 * }else{
		 * 
		 * }
		 */
		if (usernameB) {
			if (checkNumB) {
				// 邮箱验证码
				String jym = MD5Tool.MD5(RamUtil.getRandomPwd());
				HRTMember hu = new HRTMember(email, phone, pwd, "0", jym);
				hu.setMbrName(mbrName);
				hu.setSex(Integer.parseInt(sex));
				hu.setBorn(new java.sql.Date(date.getTime()));
				hu.setAge(age);
				hu.setRegisterTime(registTime);
				hrtMemberService.registerMember(hu);
				hrtMemberService.sendMail(email, jym);
				mv.addObject("hu", hu);
				mv.setViewName("/HRTWEB/loginSuccess");
			} else {
				mv.addObject("checkNumError", "验证码错误");
				mv.setViewName("/HRTWEB/register");
			}
		} else {
			mv.addObject("registerError", "用户名已存在");
			mv.setViewName("/HRTWEB/register");
		}
		return mv;
	}

	/**
	 * @param user
	 * @param request
	 * @return 会员登陆
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ModelAndView UserLogin(@ModelAttribute("userInfo") HRTMember user,
			HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();
		HttpSession session = request.getSession();
		// 从jsp中拿到值
		String email = user.getMail();
		String pwd = user.getPassword();
		String checkNum = request.getParameter("hrtMemberCheckout");
		// 根据用户名密码登陆后返回一个HRTMember对象
		HRTMember hu = hrtMemberService.loginMember(email, pwd);
		// 验证码的值
		String randCheckCode = (String) session.getAttribute("randCheckCode");
		boolean b = randCheckCode.equalsIgnoreCase(checkNum);
		if (hu != null) {
			if (b) {
				int MailCheck = hu.getIsMailVaild();
				if (MailCheck == 1) {
					session.setAttribute("HRTMember", hu);
					mv.setViewName("index");
				} else {
					mv.addObject("checkError", "用户未激活,请前往邮箱激活！");
					mv.setViewName("/HRTWEB/login");
				}
			} else {
				mv.addObject("checkError", "验证码错误");
				mv.setViewName("/HRTWEB/login");
			}
		} else {
			mv.addObject("checkError", "用户名或密码错误!");
			mv.setViewName("/HRTWEB/login");
		}
		return mv;
	}

	/**
	 * @param request
	 * @return 邮箱验证
	 */
	@RequestMapping(value = "mailCheckInfo")
	public ModelAndView mailCheckInfo(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();
		String toMail = request.getParameter("toMail");
		
		HRTMember hu = hrtMemberService.loginMember(toMail, null);

		String jym = request.getParameter("jym");
		String checkOut = hu.getMailCode();
		if (jym.equalsIgnoreCase(checkOut)) {
			hu.setIsMailVaild(1);
			hrtMemberService.updateMemberActivate(hu);
		}
		mv.setViewName("/HRTWEB/login");
		return mv;
	}

	/**
	 * @param request
	 * @return 修改密码，邮箱验证
	 */
	@RequestMapping(value = "mailCheckPass")
	public ModelAndView mailCheckPass(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();

		mv.setViewName("/HRTWEB/center");
		return mv;
	}

	@RequestMapping(value = "/check", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> checkUser(@RequestParam String uname) {
		Map<String, Object> map = new HashMap<String, Object>();
		boolean b = hrtMemberService.findMember(uname);
		map.put("checkValue", b);
		return map;
	}

	/**
	 * @param request
	 * @return 会员退出
	 */
	@RequestMapping(value = "/exit")
	public String exitUser(HttpServletRequest request) {
		HttpSession session = request.getSession();
		session.setMaxInactiveInterval(0);
		return "index";
	}

	/**
	 * @param request
	 * @return 个人中心页面
	 */
	@RequestMapping(value = "/center")
	public ModelAndView personCenter(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();

		mv.setViewName("/HRTWEB/center");
		return mv;
	}

	/**
	 * @param request
	 * @return 我的订单页面
	 */
	@RequestMapping(value = "/order")
	public ModelAndView personCenter1(HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();

		mv.setViewName("/HRTWEB/myOrder");
		return mv;
	}

	/**
	 * @param reponse
	 * @param request
	 * @return 文件上传
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public ModelAndView receiveUpload(HttpServletResponse reponse,
			HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();
		HttpSession session = request.getSession();
		
		String name = request.getParameter("PhotoName");
		System.out.println("name::" + name);
		String fileName = "E://" + name;
		// 待存储进入数据库的图片名
		String photoName = ReadFromFile.readFileByBytes(fileName, request);
		HRTMember member = (HRTMember) session.getAttribute("HRTMember");
		member.setPic(photoName);
		hrtMemberService.updateHRTMember(member);
		System.out.println("上传成功");
		mv.setViewName("/HRTWEB/center");
		return mv;
	}

	/**
	 * @param reponse
	 * @param request
	 * @return
	 * @return 文件上传
	 */
	@RequestMapping(value = "/uploadtest", method = RequestMethod.POST)
	public ModelAndView receiveUploadtest(HttpServletResponse reponse,
			HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();

		List<String> fileTypes = WebParams.getFILE_TYPES();
		String name = request.getParameter("name");
		String type = request.getParameter("type");
		String size = request.getParameter("size");
		Long sizeNum = Long.parseLong(size);
		System.out.println("sizeNum" + sizeNum);

		if ((sizeNum >= 2024000) || fileTypes.contains(type)) {
			mv.setViewName("manage/member/error");
			return mv;
		} else {
			System.out.println("type::" + type);
			System.out.println("size::" + size);
			String str = null;
			try {
				
				str = new String(name.getBytes("8859_1"), "utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}

			
			
			System.out.println("name::" + str);
			String fileName = "E://" + str;
			// 待存储进入数据库的图片名
			ReadFromFile.readFileByBytes(fileName, request);

			return null;
		}
	}

	/**
	 * 显示图片
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value = "/showImage")
	public ModelAndView showImage(
			@RequestParam(value = "saveImg", required = true) String imgUrl,
			HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		FileInputStream hFile = new FileInputStream(imgUrl); // 以byte流的方式打开文件d:\1.gif
		int i = hFile.available(); // 得到文件大小
		byte data[] = new byte[i];
		hFile.read(data); // 读数据
		response.setContentType("image/*"); // 设置返回的文件类型
		OutputStream toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
		toClient.write(data); // 输出数据

		toClient.flush();
		toClient.close();
		hFile.close();

		return null;
	}

	/**
	 * @param member
	 * @param request
	 * @return 修改个人信息
	 */
	@RequestMapping(value = "/reset")
	public ModelAndView resetMethod(
			@ModelAttribute("resetInfo") HRTMember member,
			HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();
		String isMobileVaild = request.getParameter("isMobileVaild");
		int isMobileVaildInt = Integer.parseInt(isMobileVaild);
		HttpSession session = request.getSession();
		member.setIsMailVaild(isMobileVaildInt);
		session.setAttribute("HRTMember", member);
		hrtMemberService.updateHRTMember(member);
		mv.setViewName("/HRTWEB/center");
		return mv;
	}

	/**
	 * @param member
	 * @param request
	 * @return 修改密码
	 */
	@RequestMapping(value = "/resetPass")
	public ModelAndView resetPass(
			@ModelAttribute("resetPassInfo") HRTMember member,
			@RequestParam(value = "id", required = true) String id,
			HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();
		member = this.hrtMemberService.getMemberByid(new Long(id));
		System.out.println("进来了");
		// 验证旧密码是否与用户所输入的密码一致
		String oldPass = request.getParameter("Old_password");
		String old = MD5Tool.MD5(oldPass);
		if (old.equals(member.getPassword())) {
			String newPass = request.getParameter("New_password");
			String password = MD5Tool.MD5(newPass);
			member.setPassword(password);
			hrtMemberService.updateHRTMember(member);
			mv.setViewName("/HRTWEB/center");

		} else {
			mv.addObject("error", "原密码错误");
			mv.setViewName("/HRTWEB/passError");
		}
		return mv;
	}

	/**
	 * @param request
	 * @return 验证密码
	 */
	@RequestMapping(value = "/validate", method = RequestMethod.POST)
	@ResponseBody
	public String validatePass(HttpServletRequest request) {
		String memberId = request.getParameter("id");
		String pass = request.getParameter("Old_password");
		String password = MD5Tool.MD5(pass);
		HRTMember member = this.hrtMemberService.getMemberByid(new Long(
				memberId));
		if (password.equals(member.getPassword())) {
			System.out.println("成功了");
			return "success";
		}
		System.out.println("失败了");
		return "error";
	}

	@RequestMapping(value = "/sentEmail")
	public ModelAndView returnPass(
			@RequestParam(value = "id", required = true) String id,
			HttpServletRequest request) {
		ModelAndView mv = new ModelAndView();
		String email = request.getParameter("email");
		String pass = request.getParameter("password");
		String password = MD5Tool.MD5(pass);
		HRTMember member = this.hrtMemberService.getMemberByid(new Long(id));
		member.setPassword(password);
		hrtMemberService.updateHRTMember(member);
		hrtMemberService.sendMailPass(email, pass);
		mv.setViewName("/HRTWEB/center");
		return mv;
	}

}
